"""Test script to verify all data models are properly implemented."""
import uuid
from datetime import datetime
from app import create_app, db
from app.models import User, POI, Route, WalkingSession, Music
from app.models.location import Location
from app.models.weather_data import WeatherData


def test_models():
    """Test all data models."""
    app = create_app('development')
    
    with app.app_context():
        # Clear existing data
        db.drop_all()
        db.create_all()
        
        print("✓ Database tables created successfully")
        
        # Test User model
        user = User(
            id=str(uuid.uuid4()),
            wechat_openid='test_openid_123',
            nickname='测试用户',
            avatar_url='https://example.com/avatar.jpg',
            home_latitude=39.9042,
            home_longitude=116.4074,
            home_accuracy=10.0,
            preferences={'theme': 'light'}
        )
        db.session.add(user)
        db.session.commit()
        print(f"✓ User model created: {user.to_dict()}")
        
        # Test Location model (Pydantic)
        location = Location(
            latitude=39.9042,
            longitude=116.4074,
            altitude=50.0,
            accuracy=10.0
        )
        print(f"✓ Location model created: {location.model_dump()}")
        
        # Test POI model
        poi = POI(
            id=str(uuid.uuid4()),
            name='天安门广场',
            latitude=39.9042,
            longitude=116.4074,
            category='历史',
            description='中国的象征性地标',
            photos=['https://example.com/photo1.jpg'],
            rating=4.8,
            tags=['历史', '文化', '地标'],
            external_id='tencent_123456'
        )
        db.session.add(poi)
        db.session.commit()
        print(f"✓ POI model created: {poi.to_dict()}")
        
        # Test Route model
        route = Route(
            id=str(uuid.uuid4()),
            start_latitude=39.9042,
            start_longitude=116.4074,
            end_latitude=39.9100,
            end_longitude=116.4200,
            waypoints=[
                {'latitude': 39.9050, 'longitude': 116.4100},
                {'latitude': 39.9080, 'longitude': 116.4150}
            ],
            distance_meters=1500.0,
            estimated_duration=20,
            target_poi_id=poi.id
        )
        db.session.add(route)
        db.session.commit()
        print(f"✓ Route model created: {route.to_dict()}")
        
        # Test WalkingSession model
        session = WalkingSession(
            id=str(uuid.uuid4()),
            user_id=user.id,
            route_id=route.id,
            start_time=datetime.utcnow(),
            visited_poi_ids=[],
            current_latitude=39.9042,
            current_longitude=116.4074,
            status='active',
            total_distance=0.0,
            generated_music_ids=[],
            route_history=[route.id]
        )
        db.session.add(session)
        db.session.commit()
        print(f"✓ WalkingSession model created: {session.to_dict()}")
        
        # Test WeatherData model (Pydantic)
        weather = WeatherData(
            temperature=22.5,
            condition='晴',
            humidity=65,
            wind_speed=12.5,
            aqi=50,
            timestamp=datetime.utcnow()
        )
        print(f"✓ WeatherData model created: {weather.model_dump()}")
        
        # Test Music model
        music = Music(
            id=str(uuid.uuid4()),
            user_id=user.id,
            session_id=session.id,
            poi_id=poi.id,
            file_url='https://example.com/music.mp3',
            duration=180,
            meta_info={
                'weather': '晴',
                'location': '天安门广场',
                'generated_at': datetime.utcnow().isoformat()
            }
        )
        db.session.add(music)
        db.session.commit()
        print(f"✓ Music model created: {music.to_dict()}")
        
        # Verify relationships
        user_from_db = User.query.filter_by(id=user.id).first()
        assert user_from_db is not None
        assert len(list(user_from_db.sessions)) == 1
        assert len(list(user_from_db.music_library)) == 1
        print("✓ User relationships verified")
        
        session_from_db = WalkingSession.query.filter_by(id=session.id).first()
        assert session_from_db.user.id == user.id
        assert session_from_db.route.id == route.id
        print("✓ Session relationships verified")
        
        music_from_db = Music.query.filter_by(id=music.id).first()
        assert music_from_db.user.id == user.id
        assert music_from_db.session.id == session.id
        assert music_from_db.poi.id == poi.id
        print("✓ Music relationships verified")
        
        print("\n" + "="*50)
        print("✅ All data models are properly implemented!")
        print("="*50)
        print("\nModel Summary:")
        print(f"  - User: ✓ (with home location support)")
        print(f"  - Location: ✓ (Pydantic model)")
        print(f"  - POI: ✓ (with category, photos, rating, tags)")
        print(f"  - Route: ✓ (with waypoints, distance, duration)")
        print(f"  - WalkingSession: ✓ (with status, visited POIs, route history)")
        print(f"  - WeatherData: ✓ (Pydantic model)")
        print(f"  - Music: ✓ (with metadata)")
        print("\nAll relationships are working correctly!")


if __name__ == '__main__':
    test_models()
